/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.ufc.quixada.adrs.comandos.admin;

import br.ufc.quixada.adrs.interfaces.Comando;
import br.ufc.quixada.adrs.model.Adrs;
import br.ufc.quixada.adrs.model.Prazo;
import br.ufc.quixada.adrs.service.AdrsService;
import br.ufc.quixada.adrs.service.PrazoService;
import br.ufc.quixada.adrs.util.Msg;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Welligton
 */
public class CmdAddAdrsVariosPrazos implements Comando {

    public String executa(HttpServletRequest request, HttpServletResponse response) {

        HttpSession sessao = request.getSession(true);
        AdrsService as = new AdrsService();
        PrazoService ps = new PrazoService();
        Prazo prazo = null;
        Adrs adrs = null;

        boolean cb2 = request.getParameter("cb") != null ? true : false;
        if (cb2) {
            String cb[] = request.getParameterValues("cb");
            for (int i = 0; i < cb.length; i++) {
                adrs = as.getAdrsById(Long.parseLong(retornarPrimeiraString(cb[i])));
                prazo = ps.getPrazoById(Long.parseLong(retornarSegundaString(cb[i])));
                prazo.getListaAdrs().add(adrs);
                ps.updatePrazo(prazo);
            }
        } else {
            sessao.setAttribute("erro", Msg.EMPTY_SELECTION_ERROR_ADRS);
            return "/admin/admin_add_adrs_prazos.jsp";
        }
        sessao.setAttribute("sucesso", Msg.SUCCESSFULLY_ADDED);
        return "/admin/admin_gerenciar_prazo.jsp";
    }

    private String retornarPrimeiraString(String dados) {
        String temp = "";
        for (int i = 0; i < dados.length(); i++) {
            if (dados.charAt(i) == '+') {
                break;
            } else {
                temp = temp + dados.charAt(i);
            }
        }
        return temp;
    }

    private String retornarSegundaString(String dados) {
        String temp = "";
        boolean entrou = false;
        for (int i = 0; i < dados.length(); i++) {
            if (dados.charAt(i) == '+') {
                entrou = true;
                for (int j = i + 1; j < dados.length(); j++) {
                    temp = temp + dados.charAt(j);
                }
            } else if (entrou) {
                break;
            }
        }
        return temp;
    }
}
